<script lang="ts" setup>
import * as Yup from 'yup'
import NoGetCode from '../verify/_com/NoGetCode.vue'

defineOptions({
  name: 'LoginLong',
})
definePageMeta({
  layout: 'other',
})
const router = useRouter()
const appStore = useAppStore()

const isCountdown = ref(true)
const { start, reset, current } = useCountDown({
  time: 60 * 1000,
  onFinish() {
    isCountdown.value = false
  },
})
const code = ref('')
const paramsString = window.location.search
const searchParams = new URLSearchParams(paramsString)
const curA = ref(searchParams.get('a') || '')
const curU = ref(searchParams.get('u') || '')
const curP = ref(searchParams.get('p') || '')
const isPop = ref(false)

const schema = Yup.object().shape({
  code: Yup.string(),
})
function onBack() {
  router.back()
}
// 长时间未登录验证
const { runAsync: runMemberVerify } = useRequest(ApiMemberVerify)

function onReset() {
  reset()
  start()
  isCountdown.value = true
}
function validCode() {
  if (!payPasswordReg.test(code.value))
    return curA.value.includes('@') ? $t('validate_msg_regexp_code') : $t('validate_msg_regexp_code_phone')
  return ''
}
// 验证
async function onSubmit() {
  const res = await validCode()
  if (res) {
    message.error(res)
    return
  }
  const params = {
    [curA.value.includes('@') ? 'email' : 'phone']: curA.value,
    username: curU.value || '',
    password: curP.value || '',
    captcha: code.value,
  }
  runMemberVerify(params).then((res) => {
    appStore.setToken(res)
    message.success(`${$t('welcome_guest')} ${curU.value}`)
    i18nNavigateTo('/casino')
  })
}

function onResend() {
  if (isCountdown.value)
    return
  const params = {
    [curA.value.includes('@') ? 'email' : 'phone']: curA.value,
    username: curU.value,
    password: curP.value,
    captcha: '',
  }
  runMemberVerify(params).then(() => {
    onReset()
  })
}
// 脱敏处理
function maskData(data: string) {
  // 判断是否是邮箱
  const emailRegex = /^[\w.%+-]+@[a-z0-9.-]+\.[a-z]{2,}$/i
  if (emailRegex.test(data)) {
    // 如果是邮箱，处理用户名和域名部分
    const [username, domain] = data.split('@') // 拆分用户名和域名部分
    // 保留用户名的前三个字符，中间部分用****代替，保留@及域名部分
    return `${username.substring(0, 3)}****` + `@${domain}`
  }
  else {
    // 如果是手机号，保留前3位和后4位，中间部分用*代替
    return `${data.substring(0, 3)}****${data.substring(7)}`
  }
}
function goLogin() {
  i18nNavigateTo('/login/signin')
}
onMounted(() => {
  start()
})
</script>

<template>
  <div class="h-full">
    <div class="size-full bg-[#232626]">
      <div class="relative w-full">
        <BaseImage url="/images/webp/header/h5-header.png" alt="" class="w-full aspect-[414/237]" />
        <div class="absolute top-0 w-full flex justify-between items-center px-6 py-3">
          <div>logo</div>
          <BaseButton class="w-8 !h-8 bg-[rgba(255,255,255,.05)] rounded" type="none" @click="onBack">
            <BaseIcon name="uni-close" class="text-xl" />
          </BaseButton>
        </div>
      </div>

      <div class="py-5 px-6 relative w-full">
        <div class="w-full mb-3">
          <div class="text-base font-semibold mb-1.5">
            {{ $t('verify_account') }}
          </div>

          <div class="text-[#A8AEB0] text-xs font-extrabold">
            {{ $t('please_input_your_verification_code2', [maskData(curA), 30]) }}
          </div>
        </div>
        <div class="mb-3">
          <BaseForm :schema="schema" @submit="onSubmit">
            <BaseInput
              name="code"
              required
              class="mb-3"
              :placeholder="$t('verify_code')"
              @update:model-value="v => (code = v)"
            >
              <template #right-icon>
                <BaseButton
                  v-if="isCountdown"
                  disabled
                  class="bg-[#3A4142] text-[#B3BEC1] text-sm h-8 p-1.5 py-0 -mr-1 font-bold rounded-lg"
                  type="none"
                  style="box-shadow: 0px -2px 0px 0px #323738 inset"
                >
                  {{ current.seconds }}S {{ $t('send_again') }}
                </BaseButton>
                <BaseButton
                  v-else
                  class="text-sm h-8 p-1.5 -mr-1 font-bold rounded-lg"
                  @click="onResend"
                >
                  {{ $t('resend') }}
                </BaseButton>
              </template>
            </BaseInput>
            <BaseButton type="primary" html-type="submit" class="w-full text-xs h-10">
              {{ $t('submit') }}
            </BaseButton>
          </BaseForm>
          <BaseButton type="none" class="text-[#24EE89] mt-1 text-xs font-semibold" @click="() => isPop = true">
            {{ $t('no_get_code') }}
          </BaseButton>
          <div class="py-2 text-xs border-dashed text-center text-[#FC3C3C] font-extrabold rounded-md border pointer-events-none">
            {{ $t('your_account_long_time_no_login') }}
          </div>
          <div class="center mt-4 font-extrabold text-[#B3BEC1]" @click="goLogin">
            <BaseIcon name="uni-arrow-down" class="text-base mr-.5 rotate-90" />{{ $t('return_login') }}
          </div>
          <BaseBob v-model:show="isPop" :header="$t('no_get_code')">
            <NoGetCode />
          </BaseBob>
        </div>
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped></style>
